import {
    menuRouter,
    setTagNavListInSessionStorage,
    getTagNavListInSessionStorage,
    getHomeRoute,
    routeHasExist,
    routeEqual,
    closePage,
} from '@/libs/util';
import routes from '@/router/routes';

export default {
    namespaced: true,
    state: {
        homeRoute: {}, // 首页路由
        tagNavList: [], // 标签页
        lang: JSON.parse(sessionStorage.getItem('LANGUAGE')) || [], // 语言选择
    },
    getters: {
        menuList: (state, getters, rootState) => menuRouter(routes, rootState.user.access),
    },
    mutations: {
        updateLang(state, lang) {
            state.lang = lang;
            sessionStorage.setItem('LANGUAGE', JSON.stringify(lang));
        },
        setHomeRoute(state, routers) {
            state.homeRoute = getHomeRoute(routers);
        },
        setTagNavList(state, list) {
            let tagList = [];
            if (list) {
                tagList = [...list];
            } else tagList = getTagNavListInSessionStorage() || [];
            state.tagNavList = tagList;
            setTagNavListInSessionStorage([...tagList]);
        },
        addTag(state, { route, type = 'unshift' }) {
            if (!routeHasExist(state.tagNavList, route)) {
                if (type === 'push') state.tagNavList.push(route);
                else if (route.name === 'home') state.tagNavList.unshift(route);
                else state.tagNavList.splice(1, 0, route);
                setTagNavListInSessionStorage([...state.tagNavList]);
            }
        },
        closeTag(state, route) {
            const tag = state.tagNavList.filter(item => routeEqual(item, route));
            route = tag[0] ? tag[0] : null;
            if (!route) return;
            closePage(state, route);
        },
    },
    actions: {},
};
